from slugify import slugify

from buondua.scripts.telegram_bot import TelegramBot
from buondua.scripts.telegraph import Telegraph
from buondua.models import db, MODELS, Album, Picture

import argparse

parser = argparse.ArgumentParser(
    prog='buondua-telegram-send',
    description='A script for pushing pictures to telegram',
    epilog='...'
)
subparsers = parser.add_subparsers(
    title='Commands',
    required=True,
    dest='command'
)
album_parser = subparsers.add_parser(
    'push',
    help='Push one album'
)
album_parser.add_argument(
    'album',
    type=str,
    help='A album id or url'
)
auto_parser = subparsers.add_parser(
    'auto',
    help='Automatic find and send albums to telegram'
)
auto_parser.add_argument(
    '--limit',
    type=int,
    default=10,
    dest='limit',
    help='A limit sendind albums to telegram'
)


def health_check_database():
    db.execute_sql('SELECT 1;')
    db.execute_sql('SELECT 1 FROM album;')
    db.execute_sql('SELECT 1 FROM picture;')


def main():
    telegraph = Telegraph()
    telegram_bot = TelegramBot()

    args = parser.parse_args()
    print(args)

    try:
        db.connect(reuse_if_open=True)
        db.create_tables(MODELS)
        health_check_database()

        if args.command == 'push':
            if args.album.isdecimal():
                album = Album.select().where(Album.id == int(args.album)).get()
            else:
                album = Album.select().where(Album.album_url == args.album).get()
            albums = [album]
        elif args.command == 'auto':
            albums = [a for a in Album.select().where(Album.parsed == 0).limit(args.limit)]
        else:
            albums = []

        for album in albums:
            pictures = [
                p.url
                for p in Picture.select().where(Picture.album_id == album)
            ]

            if not album.telegraph_url:
                article_url = telegraph.push_album(pictures, album.title, album.album_url)
                if not article_url:
                    raise Exception('Telegraph Error')
                album.telegraph_url = article_url
                album.save()
            else:
                article_url = album.telegraph_url

            tags = ' '.join(
                map(
                    lambda x: '\\#' + slugify(x).replace('-', '\\_'),
                    album.tags.split(',')
                )
            )
            resp = telegram_bot.send_message(
                f'[view content]({article_url})\n\n\\#pretty {tags}'
            )

            if not resp.ok:
                raise Exception('Telegram bot Error:', resp.status_code, resp.content)
            else:
                album.parsed = True
                album.save()
    except Exception as e:
        print(e)
    finally:
        if not db.is_closed():
            db.close()


if __name__ == "__main__":
    main()
